from fresh.utils.utils import *
from ..myModels.productModel import *
from ..myModels.cartModel import *

from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework.decorators import api_view
from rest_framework.response import Response


@swagger_auto_schema(method='post', manual_parameters=get_schema_prams([
    ('productId', '商品编号', openapi.TYPE_STRING, True)
]))
@api_view(['post'])
def cart_add(request):
    user_id = request.session.get('session')
    product_id = get_param(request, 'productId')

    if not user_id:
        return success('你还没登录')
    if not product_id:
        return fail('缺少productId')

    product = Product.objects.filter(id=product_id).first()
    cart = Cart.objects.filter(user_id=user_id, product_id=product_id).first()
    if not cart:
        obj = {
            "buyNum": 1,
            "imgUrl": product.banners.split(',')[0],
            "masterName": product.masterName,
            "price": product.minPrice,
            "product_id": product.id,
            "slaveName": product.slaveName,
            "user_id": user_id,
        }
        cart = Cart.objects.create(**obj)
    else:
        cart.buyNum = cart.buyNum + 1
        cart.save()

    return success(m_to_d(cart))


@api_view(['post'])
def cart_all(request):
    user_id = request.session.get('session')
    if not user_id:
        return fail("session已过期或未登录")
    values = Cart.objects.filter(user_id=user_id).values()
    return success(list(values))


@swagger_auto_schema(method='post', manual_parameters=get_schema_prams([
    ('id', 'id', openapi.TYPE_STRING, True),
    ('buyNum', 'buyNum', openapi.TYPE_STRING, True)
]))
@api_view(['post'])
def cart_update(request):
    try:
        cart_id = get_param(request, 'id')
        buy_num = get_param(request, 'buyNum')
        Cart.objects.filter(id=cart_id).update(buyNum=buy_num)
        cart = Cart.objects.get(id=cart_id)
        res_data = m_to_d(cart)
        return success(res_data)
    except Exception as e:
        return fail(str(e))


@swagger_auto_schema(method='post', manual_parameters=get_schema_prams([
    ('id', 'id', openapi.TYPE_STRING or openapi.TYPE_NUMBER, True)
]))
@api_view(['post'])
def cart_del(request):
    try:
        cart_id = get_param(request, 'id')
        if not cart_id:
            return fail('缺少id')
        cart_id = cart_id.split(',')
        id_list = [int(i) for i in cart_id]
        # res_data = Cart.objects.filter(id__in=id_list).delete()
        # return success(delete_count=res_data[0])
        return success('删除成功')
    except Exception as e:
        return fail(str(e))
